package com.tutu.collect.controller;

import cn.hutool.core.collection.CollUtil;
import com.tutu.collect.service.CollectService;
import com.tutu.commons.pojo.Collect;
import com.tutu.commons.utils.CollectError;
import com.tutu.commons.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @ @Version: 1.0
 * @Create: 2022-12-20 16:46
 **/
@Slf4j
@RestController
@RequestMapping("/collect")
@Api("用户收藏相关api")
public class CollectController {

    @Autowired
    private CollectService collectService;


    /**
     * 根据用户id查询用户收藏商品
     *
     * @param userId 用户id
     * @return 返回结果集合
     */
    @GetMapping("/list/{userId}")
    @ApiOperation(value = "根据用户id查询用户收藏商品")
    public R list(@PathVariable("userId") Integer userId) {
        List<Object> products = collectService.getCollectByUserId(userId);
        if (CollUtil.isEmpty(products)) {
            return R.fail("商品服务查询错误!");
        }
        return R.ok(products);
    }

    /**
     * 用户添加喜欢商品
     *
     * @param collect 用户收藏实体类
     * @param result  返回检验结果集
     * @return 返回结果实体集
     */
    @PostMapping("/save")
    @ApiOperation("用户添加喜欢商品")
    public R save(@RequestBody @Validated Collect collect, BindingResult result) {
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return collectService.saveCollect(collect);
    }

    /**
     * 删除收藏商品
     *
     * @param collect 用户收藏实体类
     * @param result  返回检验结果集
     * @return 返回结果实体集
     */
    @PostMapping("/remove")
    @ApiOperation("删除收藏商品")
    public R remove(@RequestBody @Validated Collect collect, BindingResult result) {
        if (result.hasErrors()) {
            String errorInfo = CollectError.getErrorInfo(result);
            return R.fail(errorInfo);
        }
        return collectService.removeCollect(collect) > 0 ? R.ok("删除成功!") : R.fail("删除失败");
    }


}
